/**
 * hex颜色转rgb颜色
 * @param str 颜色值字符串
 * @returns 返回处理后的颜色值
 */
export function hexToRgb(str: string): number[] | undefined {
	const reg = /^#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(str)) {
		ElMessage.warning('输入错误的hex');
		return undefined;
	}
	str = str.replace('#', '');
	const hexs = str.match(/../g);
	if (!hexs) {
		ElMessage.warning('输入错误的hex');
		return undefined;
	}
	const result: number[] = [];
	for (let i = 0; i < 3; i++) result[i] = parseInt(hexs[i], 16);
	return result;
}

/**
 * rgb颜色转Hex颜色
 * @param r 代表红色
 * @param g 代表绿色
 * @param b 代表蓝色
 * @returns 返回处理后的颜色值
 */
export function rgbToHex(r: number, g: number, b: number): string | undefined {
	const reg = /^\d{1,3}$/;
	if (!reg.test(r.toString()) || !reg.test(g.toString()) || !reg.test(b.toString())) {
		ElMessage.warning('输入错误的rgb颜色值');
		return undefined;
	}
	const hexs = [r.toString(16), g.toString(16), b.toString(16)];
	for (let i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`;
	return `#${hexs.join('')}`;
}

/**
 * 添加颜色透明度
 * @param color 颜色值字符串
 * @param level 透明度的程度，限0-1之间
 * @returns 返回处理后的颜色值
 */
export function getTransparenColor(color: string, level: number): string | undefined {
	const reg = /^#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(color)) {
		ElMessage.warning('输入错误的hex颜色值');
		return undefined;
	}
	const rgb = hexToRgb(color);
	if (!rgb) return undefined;
	return `rgba(${rgb[0]},${rgb[1]},${rgb[2]}, ${level})`;
}

/**
 * 加深颜色值
 * @param color 颜色值字符串
 * @param level 加深的程度，限0-1之间
 * @returns 返回处理后的颜色值
 */
export function getDarkColor(color: string, level: number): string | undefined {
	const reg = /^#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(color)) {
		ElMessage.warning('输入错误的hex颜色值');
		return undefined;
	}
	const rgb = hexToRgb(color);
	if (!rgb) return undefined;
	const result: number[] = [];
	for (let i = 0; i < 3; i++) result[i] = Math.round(20.5 * level + rgb[i] * (1 - level));
	return rgbToHex(result[0], result[1], result[2]);
}

/**
 * 变浅颜色值
 * @param color 颜色值字符串
 * @param level 加深的程度，限0-1之间
 * @returns 返回处理后的颜色值
 */
export function getLightColor(color: string, level: number): string | undefined {
	const reg = /^#?[0-9A-Fa-f]{6}$/;
	if (!reg.test(color)) {
		ElMessage.warning('输入错误的hex颜色值');
		return undefined;
	}
	const rgb = hexToRgb(color);
	if (!rgb) return undefined;
	const result: number[] = [];
	for (let i = 0; i < 3; i++) result[i] = Math.round(255 * level + rgb[i] * (1 - level));
	return rgbToHex(result[0], result[1], result[2]);
}
